import toast from '../../common/service/toast-service';
import {getVerifyCode, loginOrRegister, postEncryptData, updateUser} from '../../data-model/model-login';
import {getWxUserInfo, openSetting} from '../../common/service/system-service';
import {cleanCourseGlobalData} from '../../common/service/courses-service';
import {navigateBack, switchTab} from '../../common/service/page-service';
import {LOGIN_STATUS, EVENT_BUS_KEY} from '../../common/constants';
import {eventBusGetter} from '../../utils/eventbus';
import userService from '../../common/service/user-service';
import alertService from '../../common/service/alter-service';
import {formIdCollect} from '../../data-model/model-form';
// import {globalData} from '../../utils/global-data';
import {wxCheckSession} from '../../common/service/login-service';

let pageConf = {
    data: {
        // 倒计时控件参数
        customPhoneNumber: '',
        countdown: 60,
        verifyCodeEnable: true, // 防止验证码连点验证码按钮
        showCountDown: false, // 是否显示验证码
        lastCountDownTime: '60秒', // 初始化倒计时时间
        afterSwitchHome: false,
        avatar: '',
        name: '',
        userId: '',
        unionId: undefined,
        isShowReAuthorityModal: false,
        isShown: false

    },

    setTime () {
        let that = this;
        if (that.data.countdown <= 0) {
            // 隐藏倒计时
            that.setData({
                verifyCodeEnable: true,
                showCountDown: false
            });
            that.data.countdown = 60;
            return;
        } else {
            // 显示倒计时
            that.setData({
                showCountDown: true,
                lastCountDownTime: that.data.countdown + '秒'
            });
            let value = that.data.countdown;
            value--;
            that.data.countdown = value;
        }
        setTimeout(() => {
            that.setTime();
        }, 1000);
    },
    // region lifecycle
    onLoad (options) {
        // 登录或注册后该页面的行为
        this.data.afterSwitchHome = options.afterSwitchHome;
    },
    onShow () {
        if (!this.data.isShown) {
            this.data.isShown = true;
            console.log('onShow, 处理授权逻辑');
            this.handleAuthority();
        }
    },
    onUnload () {
        // 重置 防止线程还在执行
        this.data.countdown = 0;
    },
    // endregion
    // region click method
    onClickVerify () {
        let that = this;
        // region 表单验证
        if (this.data.customPhoneNumber.length === 0) {
            toast.showLoadingToast('请输入手机号');
            return;
        }

        if (!/^1\d{10}$/.test(this.data.customPhoneNumber)) {
            toast.showLoadingToast('手机号格式错误');
            return;
        }
        // endregion
        console.log(this.data.verifyCodeEnable);
        if (this.data.verifyCodeEnable) {
            // 防止重复请求验证码
            this.data.verifyCodeEnable = false;
            // 执行注册或登录
            getVerifyCode({'phone': this.data.customPhoneNumber})
                .then(res => {
                    that.startCountDown();
                })
                .catch(err => {
                    console.log(err);
                    that.stopCountDown();
                });
        }
    },
    // endregion
    startCountDown () {
        this.setData({
            showCountDown: true
        });
        this.setTime();
    },

    stopCountDown () {
        this.data.verifyCodeEnable = true;
    },

    onPhoneChange (e) {
        this.data.customPhoneNumber = e.detail.value;
    },

    fromSubmit (fromData) {
        let that = this;
        formIdCollect(fromData.detail.formId);
        // region 表单验证
        let form = fromData.detail.value;
        if (form.phoneNumber.length === 0) {
            toast.showLoadingToast('请输入手机号');
            return;
        }

        if (!/^1\d{10}$/.test(form.phoneNumber)) {
            toast.showLoadingToast('手机号格式错误');
            return;
        }
        if (form.verifyCode.length === 0) {
            toast.showLoadingToast('请输入验证码');
            return;
        }
        if (form.verifyCode.length < 4) {
            toast.showLoadingToast('验证码有误');
            return;
        }
        // endregion
        // 执行登录或注册
        toast.showLoading();
        loginOrRegister(form.phoneNumber, form.verifyCode, {unionId: that.data.unionId})
            .then(userInfo => {
                console.log('登录/注册成功', userInfo);
                // 判断有没有用户头像和姓名 如果没有就是新用户 需要上传微信头像与微信昵称
                if (!userInfo.userName && !userInfo.userAvatar) {
                    console.log('无姓名头像, 需要上传微信姓名头像', userInfo);
                    that.updateUserInfo(userInfo);
                    toast.hideLoading();
                } else {
                    console.log('有姓名头像 直接执行关闭页面， userinfo', userInfo);
                    userService.saveUserData(userInfo);
                    toast.hideLoading();
                    that.executeBack();
                }
            })
            .catch(err => {
                console.log('登录失败', err);
                if (err && err.header && err.header.msg) {
                    let respCode = err.statusCode;
                    if ([810, 813, 814, 817, 860].indexOf(respCode) > 0) {
                        let errMsg = decodeURI(err.header.msg);
                        toast.showLoadingToast(errMsg);
                    }
                } else {
                    toast.showLoadingToast('登录失败');
                }
            });
    },
    updateUserInfo (userInfo) {
        let that = this;
        if (that.data.avatar || that.data.name) {
            toast.showLoading();
            updateUser({
                userId: userInfo.userId,
                userAvatar: that.data.avatar ? that.data.avatar : '',
                userName: that.data.name ? that.data.name : ''
            })
                .then(userInfo => {
                    userService.saveUserData(userInfo);
                    console.log('更新头像姓名成功并保存, uid:', userInfo.userId, 'userinfo:', userInfo);
                    toast.hideLoading();
                    that.executeBack();
                })
                .catch(err => {
                    console.log('更新头像姓名失败', err);
                    if (err.header && err.header.msg) {
                        toast.showLoadingToast(decodeURIComponent(err.header.msg));
                    } else {
                        toast.showLoadingToast('登录失败');
                    }
                });
        } else {
            console.log('不更新头像姓名成功并保存, userinfo:', userInfo);
            userService.saveUserData(userInfo);
            this.executeBack();
        }
    },

    executeBack () {
        // 修改登录状态 发送正和岛用户登录成功通知
        userService.setLoginStatus(LOGIN_STATUS.ZH_LOGIN_SUCCESS);
        eventBusGetter().$emit(EVENT_BUS_KEY.LOGIN_STATUS_UPDATE, LOGIN_STATUS.ZH_LOGIN_SUCCESS);
        // 切换用户，清理课程的全局缓存
        cleanCourseGlobalData();
        // 返回页面
        if (this.data.afterSwitchHome) {
            switchTab({url: '/pages/index/index'});
        } else {
            navigateBack({delta: 1});
        }
    },
    showReauthoriteModal () {
        if (!this.data.isShowReAuthorityModal) {
            this.data.isShowReAuthorityModal = true;
            let that = this;
            alertService.showAlertModel({
                title: '再次授权',
                content: '您点击了拒绝授权，您在使用过程中可能会出现问题，为了保证您正常使用，请点击“前往授权”进行授权。',
                showCancel: false,
                confirmText: '前往授权'
            }).then(res => {
                that.data.isShowReAuthorityModal = false;
                if (res.confirm) {
                    console.log('点击确定跳转到设置', res);
                    // 打开授权设置
                    that.handleOpenSetting();
                } else {
                    console.log('没点击确定再次授权', res);
                    that.showReauthoriteModal();
                }
            }).catch(err => {
                console.log('弹窗错误再次弹窗', err);
                that.data.isShowReAuthorityModal = false;
                that.showReauthoriteModal();
            });
        }
    },
    handleAuthority () {
        let that = this;
        getWxUserInfo()
            .then(res => {
                console.log('已授权 处理授权逻辑');
                that.decipherData(res.encryptedData, res.iv);
                that.setData({
                    name: res.userInfo.nickName,
                    avatar: res.userInfo.avatarUrl
                });
            })
            .catch(err => {
                console.log('未授权 处理未授权逻辑');
                that.handleNoAuthority(err);
            });
    },
    handleNoAuthority (err) {
        if (err && (err.errMsg === 'getUserInfo:fail auth deny' || err.errMsg === 'getUserInfo:fail:auth deny')) {
            console.log('未授权弹出再次授权', err);
            this.showReauthoriteModal();
        }
    },
    handleOpenSetting () {
        let that = this;
        openSetting()
            .then(data => {
                // 授权成功
                console.log('开启设置后的处理', data);
                if (data.authSetting['scope.userInfo'] === true) {
                    that.handleAuthority();
                } else {
                    console.log('设置未开启', data);
                    that.showReauthoriteModal();
                }
            })
            .catch(err => {
                console.log('设置错误', err);
                that.showReauthoriteModal();
            });
    },
    decipherData (encryptedData, iv) {
        // let zhsession = globalData('zhsession') ? globalData('zhsession') : '';
        // let headers = {'appId': APP_ID, 'zhsession': zhsession};
        // console.log('session', zhsession, 'header', headers);
        // console.log('加密数据', encryptedData, '加密向量', iv);
        let that = this;
        console.log('解密数据获取unionId');
        postEncryptData(encryptedData, iv)
            .then(res => {
                if (res.unionId) {
                    that.data.unionId = res.unionId;
                    console.log('解密成功', res);
                    // 不需要执行授权了
                    return Promise.resolve({next: false});
                } else {
                    // 解密失败 重新授权 获取unionId
                    console.log('解密获取unoinId为空, 重新解密');
                    // 由于失败 session 已被消费 需要checkSession
                    wxCheckSession();
                    setTimeout(that.handleAuthority, 1000);
                }
            })
            .catch(err => {
                console.log('解密失败', err);
                // 解密失败 重新授权 获取unionId
                // that.handleAuthority();
                wxCheckSession();
                setTimeout(that.handleAuthority, 1000);
            });
    }
};
Page(pageConf);
